package com.mzj.saas.jobs.commons;

import java.lang.reflect.Field;
import java.util.List;

/**
 * 
 * @Description
 * 
 * @Author liuyihao
 * @Date 2018年1月10日下午5:00:14
 * @Version 1.0
 */
public class UrlBuilder {
	private StringBuilder queryB;
	private String host;

	public UrlBuilder() {
		queryB = new StringBuilder();
	}

	public UrlBuilder(String host) {
		queryB = new StringBuilder();
		host(host);
	}

	public UrlBuilder paramArray(String name, List<?> value) {
		return paramArray(name, value == null ? null : value.toArray());
	}

	public UrlBuilder paramPath(String name, Object value) {
		if (name == null || value == null) {
			return this;
		}
		String p = '{' + name + '}';
		String valueStr = value.toString();
		host = host.replace(p, valueStr);
		{
			return this;
		}
	}

	public UrlBuilder paramArrayPath(String name, List<?> value) {
		return paramArray(name, value == null ? null : value.toArray());
	}

	public UrlBuilder paramArrayPath(String name, Object[] value) {
		return paramPath(name, parseArray(value));
	}

	public UrlBuilder paramArray(String name, Object... value) {
		return param(name, parseArray(value));
	}

	public UrlBuilder host(String host) {
		this.host = host;
		return this;
	}

	public UrlBuilder param(String name, Object value) {
		if (name == null || value == null) {
			return this;
		}
		queryB.append(queryB.indexOf("?") == -1 ? '?' : '&');
		queryB.append(name).append('=').append(value.toString());
		return this;
	}

	private String parseArray(Object[] value) {
		if (value == null) {
			return null;
		}
		int iMax = value.length - 1;
		if (iMax == -1) {
			return "";
		}
		StringBuilder b = new StringBuilder();
		for (int i = 0;; i++) {
			b.append(value[i]);
			if (i == iMax) {
				break;
			}
			b.append(",");
		}
		return b.toString();
	}

	@Override
	public String toString() {
		return host + queryB.toString();
	}

	public String getURL() {
		return toString();
	}

	@SuppressWarnings("rawtypes")
	public UrlBuilder paramPOJO(Object value) {
		if (value == null) {
			return this;
		}

		Field[] fields = value.getClass().getDeclaredFields();
		for (Field field : fields) {
			try {
				field.setAccessible(true);
				Object fieldValue = field.get(value);
				if (fieldValue == null) {
					continue;
				}
				if (fieldValue instanceof List) {
					this.paramArray(field.getName(), (List) fieldValue);
				} else if (fieldValue instanceof Object[]) {
					this.paramArray(field.getName(), (Object[]) fieldValue);
				} else {
					this.param(field.getName(), fieldValue);
				}
			} catch (IllegalAccessException e) {
				e.printStackTrace();
				return this;
			}
		}
		return this;
	}

}
